package com.design.chain;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 责任链处理上下文
 *
 * @author Zee
 * @date 2020年4月30日
 * @since v1.0
 */
@Component
public class ChainLinkedHandlerContext {
    private ChainLinkedHandler root;


    /**
     * 将handler关联形成链表
     *
     * @return
     */
    public void linkedHandler(Map<Integer, ChainLinkedHandler> handlers) {
        if (ObjectUtil.isNotEmpty(handlers)) {
            for (int i = 0; i < handlers.size(); i++) {
                handlers.get(i).next = handlers.get(i + 1);
            }
        }
        this.root = handlers.get(0);
    }

    /**
     * 责任链执行
     */
    public void execute() {
        ChainLinkedHandler node = root;
        while (ObjectUtil.isNotNull(node)) {
            node.execute();
            node = node.next;
        }
    }

}
